package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"novel/models/cache"
	"novel/models/mysql"
	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"
	"novel/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	findUser := mysql.User{
		Phone:     in.Phone,
		Password:  pkg.Md5(in.Password),
		HeadImage: "http://t4kawq9ae.hn-bkt.clouddn.com/",
		NickName:  fmt.Sprintf("用户_%d", rand.Intn(10000)),
	}
	err := findUser.FindUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("用户不存在,清先注册")
	}

	if in.LoginType == 1 {
		if pkg.Md5(in.Password) != findUser.Password {
			return nil, errors.New("密码错误")
		}
	}
	if in.LoginType == 2 {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
		if in.SendSmsCode == "" {
			return nil, errors.New("请输入验证码")
		}
		if result != in.SendSmsCode {
			return nil, errors.New("验证码错误")
		}

	}

	return &novelrpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
